<template>
  <view class="publish-container">
    <!-- 动态导航栏标题，如果需要自定义导航栏，可以在这里通过条件渲染实现 -->
    <!-- Uni-app 通常通过 pages.json 配置或 uni.setNavigationBarTitle 动态设置 -->
    
    <view class="form-group">
      <view class="form-item">
        <input 
          type="text"
          v-model="form.title"
          placeholder="请输入标题（必填）"
          maxlength="50"
			style="height:100rpx"
        />
      </view>
      
      <view class="form-item">
        <textarea
          v-model="form.content"
          placeholder="分享你的就医经验、问题或攻略..."
          maxlength="2000"
          :auto-height="true"
        ></textarea>
      </view>
      
      <view class="image-upload">
        <view class="image-list">
          <view 
            v-for="(img, index) in form.images" 
            :key="index"
            class="image-item"
            @tap="previewImage(index)"
          >
            <image :src="getImageUrl(img)" mode="aspectFill"></image>
            <view class="delete-btn" @tap.stop="deleteImage(index)">
              <text class="iconfont icon-close"></text>
            </view>
          </view>
          
          <view 
            class="upload-btn"
            v-if="form.images.length < 9"
            @tap="chooseImage"
          >
            <text class="iconfont icon-camera"></text>
            <text class="upload-text">上传图片</text>
          </view>
        </view>
        <text class="upload-tip">最多上传9张图片</text>
      </view>
      
      <view class="category-select">
        <picker 
          mode="selector" 
          :range="categories" 
          range-key="name"
          @change="handleCategoryChange"
        >
          <view class="picker">
            <text class="label">选择分类：</text>
            <text class="value">{{ form.category || '请选择分类' }}</text>
            <text class="iconfont icon-arrow-right"></text>
          </view>
        </picker>
      </view>
    </view>
    
    <view class="submit-btn" @tap="handleSubmit" :class="{ disabled: !isValid }">
      {{ submitButtonText }}
    </view>

    <!-- <view class="test-upload-btn" @tap="testChunkUpload">
      测试断点续传上传
    </view> -->
  </view>
</template>

<script>
import config from '@/config'
import { getToken } from '@/utils/auth'
import { addPost, updatePost, getPost } from '@/api/community' // 导入 updatePost 和 getPost
import uploadManager from '@/utils/upload' // 直接导入 uploadManager

export default {
  data() {
    return {
      form: {
        postId: null, // 新增 postId 字段，用于编辑模式
        title: '',
        content: '',
        images: [],
        category: ''
      },
      categories: [
        { name: '就医经验' },
        { name: '病友互助' },
        { name: '就医问答' },
        { name: '就医攻略' }
      ],
      isEditMode: false, // 标记是否为编辑模式
      uploadManager: null // 添加 uploadManager 实例存储
    }
  },
  created() {
    // 在 created 钩子中初始化 uploadManager
    this.uploadManager = uploadManager;
    console.log('uploadManager initialized:', this.uploadManager);
  },
  computed: {
    isValid() {
      return this.form.title && this.form.content && this.form.category
    },
    submitButtonText() {
      return this.isEditMode ? '更新' : '发布'
    }
  },
  onLoad(options) {
    if (options.postId && options.postData) {
      try {
        this.isEditMode = true
        const postData = JSON.parse(decodeURIComponent(options.postData))
        this.form.postId = postData.postId
        this.form.title = postData.title
        this.form.content = postData.content
        // 图片处理：将后端返回的完整URL或相对路径转换为可直接显示的URL
        if (postData.images && typeof postData.images === 'string') {
            this.form.images = postData.images.split(',').map(img => {
                // 确保图片路径是完整的，如果不是，则加上baseUrl
                if (img.startsWith('http://') || img.startsWith('https://')) {
                    return img;
                } else {
                    return config.baseUrl + img;
                }
            });
        } else if (Array.isArray(postData.images)) {
            this.form.images = postData.images.map(img => {
                if (img.startsWith('http://') || img.startsWith('https://')) {
                    return img;
                } else {
                    return config.baseUrl + img;
                }
            });
        } else {
            this.form.images = [];
        }
        this.form.category = postData.category
        uni.setNavigationBarTitle({
          title: '编辑帖子'
        })
      } catch (e) {
        console.error('解析帖子数据失败', e)
        uni.showToast({
          title: '加载帖子信息失败',
          icon: 'none'
        })
        this.isEditMode = false // 出错则退回发布模式
      }
    } else {
      uni.setNavigationBarTitle({
        title: '发布帖子'
      })
    }
  },
  methods: {
    // 获取完整的图片URL
    getImageUrl(url) {
      if (!url) return '';
      // 如果已经是完整URL，直接返回
      if (url.startsWith('http://') || url.startsWith('https://')) {
        return url;
      }
      // 确保url以/开头
      if (!url.startsWith('/')) {
        url = '/' + url;
      }
      return config.baseUrl + url;
    },
    
    // 预览图片
    previewImage(index) {
      // 确保urls是完整路径
      const urls = this.form.images.map(img => this.getImageUrl(img));
      uni.previewImage({
        urls: urls,
        current: urls[index]
      });
    },
    
    // 上传图片
    uploadFile(file) {
      return new Promise(async (resolve, reject) => {
        try {
          // 检查 uploadManager 是否可用
          if (!this.uploadManager) {
            this.uploadManager = uploadManager;
          }

          const options = {
            filePath: file,
            onProgress: (progress) => {
              console.log(`图片上传进度: ${progress}%`);
            },
            onSuccess: (result) => {
              console.log('上传成功，返回数据:', result);
              // 确保 URL 包含完整的服务器地址
              const fileUrl = result.url.startsWith('http') 
                ? result.url 
                : `http://localhost:8888${result.url}`;
              resolve(fileUrl);
            },
            onError: (error) => {
              console.error('图片上传错误:', error);
              reject(error);
            }
          };

          // 开始上传
          console.log('开始上传文件...');
          await this.uploadManager.startUpload(options);

        } catch (error) {
          console.error('图片上传过程发生错误：', error);
          reject(error);
        }
      });
    },
    
    // 选择图片
    async chooseImage() {
      try {
        const res = await uni.chooseImage({
          count: 9 - this.form.images.length,
          sizeType: ['compressed'],
          sourceType: ['album', 'camera']
        });
        
        // 显示上传进度
        uni.showLoading({
          title: '上传中...',
          mask: true
        });
        
        try {
          // 上传图片
          const uploadTasks = res.tempFilePaths.map(path => this.uploadFile(path));
          const uploadResults = await Promise.all(uploadTasks);
          
          console.log('上传结果:', uploadResults);
          
          // 添加到图片列表
          this.form.images = [...this.form.images, ...uploadResults];
          
          uni.hideLoading();
          uni.showToast({
            title: '上传成功',
            icon: 'success'
          });
        } catch (error) {
          uni.hideLoading();
          uni.showToast({
            title: '上传失败',
            icon: 'none'
          });
          console.error('上传图片失败：', error);
        }
      } catch (error) {
        console.error('选择图片失败：', error);
        uni.showToast({
          title: '选择图片失败',
          icon: 'none'
        });
      }
    },
    
    // 获取完整的图片URL
    getFullImageUrl(url) {
      if (!url) return '';
      const serverPrefix = 'http://localhost:8888';
      return url.startsWith('http://') ? url : serverPrefix + url;
    },
    
    // 删除图片
    deleteImage(index) {
      this.form.images.splice(index, 1)
    },
    
    // 选择分类
    handleCategoryChange(e) {
      const index = e.detail.value
      this.form.category = this.categories[index].name
    },
    
    // 提交表单
    async handleSubmit() {
      if (!this.isValid) {
        uni.showToast({
          title: '请填写完整信息',
          icon: 'none'
        });
        return;
      }
      
      try {
        const postData = { ...this.form };
        console.log('提交前的原始图片数据:', postData.images);
        
        // 处理图片数组
        if (postData.images && Array.isArray(postData.images)) {
          // 将完整URL转换为相对路径
          postData.images = postData.images.map(url => {
            // 如果是完整URL，移除baseUrl部分
            if (url.startsWith(config.baseUrl)) {
              return url.substring(config.baseUrl.length);
            }
            return url;
          }).join(',');
        } else {
          postData.images = '';
        }

        console.log('处理后的图片数据:', postData.images);

        let res;
        if (this.isEditMode) {
          console.log('publish.vue: 更新帖子参数:', postData);
          res = await updatePost(postData);
        } else {
          console.log('publish.vue: 发布帖子参数:', postData);
          res = await addPost(postData);
        }
        
        console.log('提交返回结果:', res);
        
        if (res.code === 200) {
          // 成功后立即触发刷新
          console.log('publish.vue: 操作成功，触发刷新');
          
          // 1. 设置存储标志
          uni.setStorageSync('shouldRefreshMyPosts', true);
          uni.setStorageSync('shouldRefreshCommunity', true);
          
          // 2. 发送事件通知
          uni.$emit('refreshMyPosts');
          
          // 3. 显示成功提示
          uni.showToast({
            title: this.isEditMode ? '更新成功' : '发布成功',
            icon: 'success',
            duration: 1500
          });
          
          // 4. 确保刷新事件已发出后再返回
          setTimeout(() => {
            console.log('publish.vue: 返回上一页');
            uni.navigateBack({
              delta: 1,
              success: () => {
                console.log('publish.vue: 返回成功');
                // 5. 再次触发刷新事件，以防返回时页面已重新加载
                setTimeout(() => {
                  console.log('publish.vue: 再次触发刷新事件');
                  uni.$emit('refreshMyPosts');
                }, 100);
              }
            });
          }, 1500);
        } else {
          uni.showToast({
            title: res.msg || (this.isEditMode ? '更新失败' : '发布失败'),
            icon: 'none'
          });
        }
      } catch (error) {
        console.error('publish.vue: 操作失败:', error);
        uni.showToast({
          title: '网络错误，请稍后重试',
          icon: 'none'
        });
      }
    },
    // 获取来源页面
    getFromPage() {
      const pages = getCurrentPages();
      const currentPage = pages[pages.length - 1];
      return currentPage.$page?.options?.from || '';
    },

    // 测试断点续传上传
    async testChunkUpload() {
      try {
        console.log('开始选择文件...');
        const res = await uni.chooseImage({
          count: 1,
          sizeType: ['original'],
          sourceType: ['album']
        });

        console.log('文件选择成功:', res);
        const filePath = res.tempFilePaths[0];
        
        // 检查 uploadManager 是否可用
        if (!this.uploadManager) {
          console.error('uploadManager 未初始化');
          throw new Error('上传管理器未初始化');
        }

        console.log('准备上传配置...');
        // 记录上传状态
        let currentFileId = null;
        let isPaused = false;

        const options = {
          filePath,
          onProgress: (progress) => {
            console.log(`上传进度: ${progress}%`);
            uni.showLoading({
              title: `上传中: ${Math.floor(progress)}%`,
              mask: true
            });
          },
          onSuccess: () => {
            console.log('上传成功');
            uni.hideLoading();
            uni.showToast({
              title: '上传成功',
              icon: 'success'
            });
          },
          onError: (error) => {
            console.error('上传错误:', error);
            uni.hideLoading();
            uni.showToast({
              title: '上传失败: ' + error.message,
              icon: 'none'
            });
          }
        };

        console.log('开始上传文件...');
        // 开始上传
        currentFileId = await this.uploadManager.startUpload(options);
        console.log('文件上传已开始, fileId:', currentFileId);

        // 模拟中断：3秒后暂停上传
        setTimeout(() => {
          if (currentFileId && !isPaused) {
            console.log('执行暂停上传...');
            this.uploadManager.pauseUpload(currentFileId);
            isPaused = true;
            
            // 2秒后恢复上传
            setTimeout(() => {
              if (currentFileId && isPaused) {
                console.log('执行恢复上传...');
                this.uploadManager.resumeUpload(currentFileId);
                isPaused = false;
              }
            }, 2000);
          }
        }, 3000);

      } catch (error) {
        console.error('上传过程发生错误：', error);
        uni.hideLoading();
        uni.showToast({
          title: error.message || '上传失败',
          icon: 'none',
          duration: 2000
        });
      }
    }
  }
}
</script>

<style lang="scss">
.publish-container {
  min-height: 100vh;
  background-color: #f5f5f5;
}

.form-group {
  background-color: #fff;
  margin-bottom: 20rpx;
  padding: 30rpx;
}

.form-item {
  margin-bottom: 30rpx;

  input,
  textarea {
    width: 100%;
    padding: 20rpx;
    border: 1rpx solid #eee;
    border-radius: 8rpx;
    font-size: 30rpx;
    box-sizing: border-box;
  }

  textarea {
    min-height: 200rpx;
  }
}

.image-upload {
  margin-bottom: 30rpx;

  .image-list {
    display: flex;
    flex-wrap: wrap;

    .image-item {
      position: relative;
      width: 200rpx;
      height: 200rpx;
      margin-right: 20rpx;
      margin-bottom: 20rpx;
      border-radius: 8rpx;
      overflow: hidden;

      image {
        width: 100%;
        height: 100%;
        object-fit: cover;
      }

      .delete-btn {
        position: absolute;
        top: 0;
        right: 0;
        background-color: rgba(0, 0, 0, 0.5);
        color: #fff;
        width: 40rpx;
        height: 40rpx;
        display: flex;
        justify-content: center;
        align-items: center;
        border-bottom-left-radius: 8rpx;
        font-size: 24rpx;
      }
    }

    .upload-btn {
      width: 200rpx;
      height: 200rpx;
      border: 2rpx dashed #ccc;
      border-radius: 8rpx;
      display: flex;
      flex-direction: column;
      justify-content: center;
      align-items: center;
      color: #999;
      font-size: 28rpx;

      .iconfont {
        font-size: 60rpx;
        margin-bottom: 10rpx;
      }
    }
  }

  .upload-tip {
    font-size: 24rpx;
    color: #999;
    margin-top: 10rpx;
  }
}

.category-select {
  .picker {
    display: flex;
    align-items: center;
    justify-content: space-between;
    padding: 20rpx;
    border: 1rpx solid #eee;
    border-radius: 8rpx;
    font-size: 30rpx;
    color: #333;

    .label {
      color: #666;
    }

    .value {
      flex: 1;
      text-align: right;
      margin-right: 20rpx;
    }

    .iconfont {
      font-size: 32rpx;
      color: #999;
    }
  }
}

.submit-btn {
  background-color: #1E90FF;
  color: #fff;
  font-size: 36rpx;
  text-align: center;
  padding: 25rpx 0;
  margin: 30rpx;
  border-radius: 12rpx;

  &.disabled {
    background-color: #a0cfff;
    cursor: not-allowed;
  }
}

.test-upload-btn {
  background-color: #67C23A;
  color: #fff;
  font-size: 32rpx;
  text-align: center;
  padding: 20rpx 0;
  margin: 20rpx 30rpx;
  border-radius: 12rpx;
}
</style> 